package org.zoomdev.zoom.aop.modules;

import org.zoomdev.zoom.aop.AopFactory;
import org.zoomdev.zoom.ioc.Ioc;
import org.zoomdev.zoom.ioc.IocKey;
import org.zoomdev.zoom.ioc.impl.factories.ModuleIocFactory;

import java.lang.reflect.Method;

public final class LazyEnhanceProxy implements ModuleIocFactory.IocConstructorProxy {

    /**
     * 实际要new的
     */
    private final Class type;

    private final AopFactory factory;

    private final Ioc ioc;


    private final MethodWithTypeConfig config;

    public LazyEnhanceProxy(Class type, AopFactory factory, Ioc ioc, MethodWithTypeConfig config) {
        this.type = type;
        this.factory = factory;
        this.ioc = ioc;
        this.config = config;
    }

    @Override
    public Object newInstance(ModuleIocFactory.ModuleIocConstructor constructor, IocKey resultKey, Object[] args) throws Throwable {
        Class enhanced = factory.enhance(type);
        if (enhanced == type) {
            //不需要增强
            return constructor.newInstance0(args);
        }
        //剥离方法,检查是否存在
        Class newModuleType = AsmModuleContainer.getEnhancedModule(constructor.getModuleType(),factory);
        if(newModuleType == constructor.getModuleType()){
            return constructor.newInstance0(args);
        }
        Object newModule = ioc.fetch(newModuleType);
        Method oldMethod = constructor.getMethod();
        Method newMethod = newModuleType.getDeclaredMethod(oldMethod.getName(), oldMethod.getParameterTypes());
        return newMethod.invoke(newModule, args);
    }

    @Override
    public Class getRealType() {
        return type;
    }


}
